<script>
import LocalNotificationManager from "@/utils/localNotification.js";
import audioManager from "@/utils/audioManager.js";
import backgroundService from "@/utils/backgroundService.js";

export default {
  data() {
    return {
      globalCheckTimer: null,
      triggeredAlarms: [],
      lastCheckTime: ''
    };
  },
  onLaunch: function () {
    console.log("🚀 App Launch - 启动全局闹钟检查");
    this.setupNotificationListener();
    this.startGlobalAlarmCheck();
    this.initBackgroundService();
  },
  onShow: function () {
    console.log("App Show");
    // 确保闹钟检查在应用显示时运行
    if (!this.globalCheckTimer) {
      this.startGlobalAlarmCheck();
    }
  },
  onHide: function () {
    console.log("App Hide");
    // 应用隐藏时不停止检查，保持后台运行
  },
  methods: {
    // 全局闹钟检查
    startGlobalAlarmCheck() {
      if (this.globalCheckTimer) {
        clearInterval(this.globalCheckTimer);
      }

      this.globalCheckTimer = setInterval(() => {
        this.checkGlobalAlarms();
      }, 100); // 每100ms检查一次

      console.log('🌍 全局闹钟检查已启动，定时器ID:', this.globalCheckTimer);

      // 测试定时器是否正常工作
      setTimeout(() => {
        console.log('✅ 全局定时器运行正常，5秒测试完成');
      }, 5000);
    },

    stopGlobalAlarmCheck() {
      if (this.globalCheckTimer) {
        clearInterval(this.globalCheckTimer);
        this.globalCheckTimer = null;
        console.log('🌍 全局闹钟检查已停止');
      }
    },

    checkGlobalAlarms() {
      const now = new Date();
      const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
      const currentDay = now.getDay();
      const currentDate = now.toISOString().split('T')[0];

      // 防止重复触发
      if (this.lastCheckTime === currentTime) {
        return;
      }

      if (this.lastCheckTime !== currentTime) {
        this.lastCheckTime = currentTime;
        this.triggeredAlarms = [];
      }

      // 从本地存储获取闹钟数据
      try {
        const alarmsData = uni.getStorageSync('alarms');
        if (!alarmsData) return;

        let alarms;

        // 安全的JSON解析
        if (typeof alarmsData === 'string') {
          try {
            alarms = JSON.parse(alarmsData);
          } catch (parseError) {
            console.error('JSON解析失败:', parseError);
            console.log('原始数据:', alarmsData);
            return;
          }
        } else if (Array.isArray(alarmsData)) {
          // 如果已经是数组，直接使用
          alarms = alarmsData;
        } else {
          console.error('闹钟数据格式错误:', typeof alarmsData, alarmsData);
          return;
        }

        if (!Array.isArray(alarms)) {
          console.error('闹钟数据不是数组:', alarms);
          return;
        }

        alarms.forEach(alarm => {
          if (alarm.isActive && alarm.time === currentTime) {
            const alarmKey = `${alarm.id}-${currentTime}`;

            // 防止重复触发
            if (this.triggeredAlarms.includes(alarmKey)) {
              return;
            }

            this.triggeredAlarms.push(alarmKey);

            if (alarm.type === 'once') {
              if (alarm.date === currentDate) {
                this.triggerGlobalAlarm(alarm);
                // 关闭一次性闹钟
                this.toggleGlobalAlarm(alarm.id, alarms);
              }
            } else if (alarm.type === 'repeat') {
              if (alarm.repeatDays && alarm.repeatDays.includes(currentDay)) {
                this.triggerGlobalAlarm(alarm);
              }
            } else {
              // 兼容旧版本
              if (alarm.repeatDays && alarm.repeatDays.length > 0) {
                if (alarm.repeatDays.includes(currentDay)) {
                  this.triggerGlobalAlarm(alarm);
                }
              } else {
                this.triggerGlobalAlarm(alarm);
                this.toggleGlobalAlarm(alarm.id, alarms);
              }
            }
          }
        });
      } catch (error) {
        console.error('全局闹钟检查错误:', error);
      }
    },

    async triggerGlobalAlarm(alarm) {
      console.log('🔔 全局闹钟触发:', alarm.label);

      // 震动
      if (alarm.vibrate) {
        this.performGlobalVibration();
      }

      // 播放铃声
      if (alarm.enableRingtone && alarm.ringtone) {
        try {
          console.log('🎵 播放铃声:', alarm.ringtoneName || alarm.ringtone);
          audioManager.playRingtone(alarm.ringtone, 10);
        } catch (error) {
          console.error('播放铃声失败:', error);
        }
      }

      // 显示提醒
      let modalContent = alarm.time + ' - ' + alarm.label;
      if (alarm.enableRingtone) {
        modalContent +=  (alarm.ringtoneName || '铃声');
      }

      uni.showModal({
        title: '⏰ 闹钟提醒',
        content: modalContent,
        confirmText: '知道了',
        showCancel: false,
        success: () => {
          // 用户确认后停止铃声
          audioManager.stopPlaying();
        }
      });
    },

    performGlobalVibration() {
      // #ifdef H5
      if (navigator.vibrate) {
        const vibrationPattern = [200, 100, 200, 100, 500, 100, 200];
        navigator.vibrate(vibrationPattern);

        setTimeout(() => {
          navigator.vibrate(1000);
        }, 2000);
      }
      // #endif

      // #ifndef H5
      uni.vibrate({
        success: () => {
          console.log('全局震动成功');
        }
      });

      setTimeout(() => {
        try {
          uni.vibrateLong({});
        } catch (error) {
          uni.vibrate({});
        }
      }, 800);
      // #endif
    },

    toggleGlobalAlarm(alarmId, alarms) {
      const alarmIndex = alarms.findIndex(alarm => alarm.id === alarmId);
      if (alarmIndex !== -1) {
        alarms[alarmIndex].isActive = false;
        uni.setStorageSync('alarms', JSON.stringify(alarms));
      }
    },

    setupNotificationListener() {
      // #ifdef APP-PLUS
      try {
        // 监听本地通知点击事件
        plus.push.addEventListener("click", (message) => {
          console.log("收到通知点击事件:", message);
          LocalNotificationManager.handleNotificationClick(message);
        });

        // 监听本地通知接收事件
        plus.push.addEventListener("receive", (message) => {
          console.log("收到本地通知:", message);
          // 通知到达时也可以处理震动等
          if (message.payload && message.payload.vibrate) {
            LocalNotificationManager.performVibration();
          }
        });

        console.log("通知监听器已设置");
      } catch (error) {
        console.error("设置通知监听器失败:", error);
      }
      // #endif
    },
    
    // 初始化后台服务
    async initBackgroundService() {
      console.log('🔧 初始化后台服务...');
      
      try {
        // 启动后台服务
        const success = await backgroundService.startBackgroundService();
        
        if (success) {
          console.log('✅ 后台服务初始化成功');
          
          // 检查权限并显示引导（仅在APP环境）
          // #ifdef APP-PLUS
          setTimeout(() => {
            const permissions = backgroundService.checkBackgroundPermissions();
            if (!permissions.batteryOptimization) {
              backgroundService.showPermissionGuide();
            }
          }, 3000); // 延迟3秒显示，避免启动时过多弹窗
          // #endif
          
        } else {
          console.warn('⚠️ 后台服务初始化失败');
        }
      } catch (error) {
        console.error('❌ 后台服务初始化异常:', error);
      }
    },
  },
};
</script>

<style>
/*每个页面公共css */
</style>
